route.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. import { NextRequest, NextResponse } from 'next/server';
  2. import { getServerSession } from 'next-auth';
  3. import { authOptions } from '@/lib/auth';
  4. import { prisma } from '@/lib/prisma';
  5. // PUT - Actualizar inscripción de estudiante
  6. export async function PUT(
  7. request: NextRequest,
  8. { params }: { params: Promise<{ id: string }> }
  9. ) {
  10. try {
  11. const session = await getServerSession(authOptions);
  12. if (!session || session.user.role !== 'ADMIN') {
  13. return NextResponse.json(
  14. { message: 'No autorizado' },
  15. { status: 401 }
  16. );
  17. }
  18. const { id } = await params;
  19. const body = await request.json();
  20. const { studentId, sectionId, isActive } = body;
  21. // Validaciones básicas
  22. if (!studentId || !sectionId) {
  23. return NextResponse.json(
  24. { message: 'Estudiante y sección son requeridos' },
  25. { status: 400 }
  26. );
  27. }
  28. // Verificar si la inscripción existe
  29. const existingEnrollment = await prisma.studentEnrollment.findUnique({
  30. where: { id },
  31. });
  32. if (!existingEnrollment) {
  33. return NextResponse.json(
  34. { message: 'Inscripción no encontrada' },
  35. { status: 404 }
  36. );
  37. }
  38. // Verificar si el estudiante existe y está activo
  39. const student = await prisma.student.findFirst({
  40. where: {
  41. id: studentId,
  42. isActive: true,
  43. deletedAt: null,
  44. },
  45. });
  46. if (!student) {
  47. return NextResponse.json(
  48. { message: 'El estudiante seleccionado no existe o no está activo' },
  49. { status: 400 }
  50. );
  51. }
  52. // Verificar si la sección existe y está activa
  53. const section = await prisma.section.findFirst({
  54. where: {
  55. id: sectionId,
  56. isActive: true,
  57. deletedAt: null,
  58. class: {
  59. isActive: true,
  60. deletedAt: null,
  61. period: {
  62. isActive: true,
  63. deletedAt: null,
  64. },
  65. },
  66. },
  67. include: {
  68. class: {
  69. include: {
  70. period: true,
  71. },
  72. },
  73. },
  74. });
  75. if (!section) {
  76. return NextResponse.json(
  77. { message: 'La sección seleccionada no existe, no está activa o pertenece a un período inactivo' },
  78. { status: 400 }
  79. );
  80. }
  81. // Si se está cambiando el estudiante o la sección, verificar duplicados
  82. if (studentId !== existingEnrollment.studentId || sectionId !== existingEnrollment.sectionId) {
  83. const duplicateEnrollment = await prisma.studentEnrollment.findFirst({
  84. where: {
  85. studentId,
  86. sectionId,
  87. isActive: true,
  88. id: { not: id },
  89. },
  90. });
  91. if (duplicateEnrollment) {
  92. return NextResponse.json(
  93. { message: 'El estudiante ya está inscrito en esta sección' },
  94. { status: 400 }
  95. );
  96. }
  97. }
  98. // Actualizar la inscripción
  99. const updatedEnrollment = await prisma.studentEnrollment.update({
  100. where: { id },
  101. data: {
  102. studentId,
  103. sectionId,
  104. isActive: isActive !== undefined ? isActive : existingEnrollment.isActive,
  105. },
  106. include: {
  107. student: {
  108. select: {
  109. id: true,
  110. firstName: true,
  111. lastName: true,
  112. cedula: true,
  113. email: true,
  114. phone: true,
  115. admissionNumber: true,
  116. },
  117. },
  118. section: {
  119. select: {
  120. id: true,
  121. name: true,
  122. class: {
  123. select: {
  124. id: true,
  125. name: true,
  126. code: true,
  127. period: {
  128. select: {
  129. id: true,
  130. name: true,
  131. isActive: true,
  132. },
  133. },
  134. },
  135. },
  136. },
  137. },
  138. },
  139. });
  140. return NextResponse.json(updatedEnrollment);
  141. } catch (error) {
  142. console.error('Error updating student enrollment:', error);
  143. return NextResponse.json(
  144. { message: 'Error interno del servidor' },
  145. { status: 500 }
  146. );
  147. }
  148. }
  149. // DELETE - Eliminar inscripción de estudiante
  150. export async function DELETE(
  151. request: NextRequest,
  152. { params }: { params: Promise<{ id: string }> }
  153. ) {
  154. try {
  155. const session = await getServerSession(authOptions);
  156. if (!session || session.user.role !== 'ADMIN') {
  157. return NextResponse.json(
  158. { message: 'No autorizado' },
  159. { status: 401 }
  160. );
  161. }
  162. const { id } = await params;
  163. // Verificar si la inscripción existe
  164. const enrollment = await prisma.studentEnrollment.findUnique({
  165. where: { id },
  166. });
  167. if (!enrollment) {
  168. return NextResponse.json(
  169. { message: 'Inscripción no encontrada' },
  170. { status: 404 }
  171. );
  172. }
  173. // Verificar si existen registros de asistencia asociados
  174. const attendanceCount = await prisma.attendance.count({
  175. where: {
  176. studentId: enrollment.studentId,
  177. section: {
  178. id: enrollment.sectionId,
  179. },
  180. },
  181. });
  182. if (attendanceCount > 0) {
  183. // Si existen registros de asistencia, desactivar en lugar de eliminar
  184. const deactivatedEnrollment = await prisma.studentEnrollment.update({
  185. where: { id },
  186. data: { isActive: false },
  187. });
  188. return NextResponse.json({
  189. message: 'La inscripción ha sido desactivada debido a registros de asistencia existentes',
  190. enrollment: deactivatedEnrollment,
  191. });
  192. } else {
  193. // Si no hay registros de asistencia, eliminar completamente
  194. await prisma.studentEnrollment.delete({
  195. where: { id },
  196. });
  197. return NextResponse.json({
  198. message: 'Inscripción eliminada exitosamente',
  199. });
  200. }
  201. } catch (error) {
  202. console.error('Error deleting student enrollment:', error);
  203. return NextResponse.json(
  204. { message: 'Error interno del servidor' },
  205. { status: 500 }
  206. );
  207. }
  208. }